iT邦幫忙

2026 iThome 鐵人賽

DAY 6
0
Modern Web

現在就學C# 與 ASP.NET Core系列 第 6

Day 6|Loop:讓程式重複執行

  • 分享至 

  • xImage
  •  

Day 5 我們學會使用 if / elseswitch,讓程式根據條件決定執行流程。

但如果同一段程式要執行 10 次、100 次,難道要重複寫很多次嗎?

這時就需要:

Loop(迴圈)

Loop 用來重複執行一段程式,直到條件不成立。

今天會學到:

  • for
  • while
  • do while
  • break
  • continue
  • Infinite Loop
  • Nested Loop

1. 為什麼需要 Loop?

假設要輸出 1 到 5:

Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
Console.WriteLine(4);
Console.WriteLine(5);

可以改成:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

結果:

1
2
3
4
5

Loop 的核心流程:

判斷條件
   ↓
條件成立
   ↓
執行程式
   ↓
更新狀態
   ↓
再次判斷
   ↓
條件不成立
   ↓
結束

2. for Loop

如果有明確的執行次數或計數方式,通常會使用 for

基本語法:

for (初始化; 條件; 更新)
{
    // 重複執行
}

例如:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

可以拆成:

int i = 1
↓
初始化

i <= 5
↓
是否繼續

i++
↓
每次執行後更新

for 的執行順序

例如:

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine(i);
}

流程:

i = 1
 ↓
i <= 3 ?
 ↓ true
輸出 1
 ↓
i++
 ↓
i = 2
 ↓
再次判斷

直到:

i = 4

4 <= 3
↓
false

Loop 結束。

所以 for 可以記成:

初始化
  ↓
判斷
  ↓
執行
  ↓
更新
  ↓
再次判斷

i 是什麼?

for (int i = 0; i < 5; i++)

i 只是一個 Variable Name,常用來當作計數器或 Index。

也可以使用更有意義的名稱:

for (int orderNumber = 1; orderNumber <= 5; orderNumber++)
{
    Console.WriteLine(orderNumber);
}

為什麼常常從 0 開始?

實務上常看到:

for (int i = 0; i < 5; i++)

因為 Array、List 等集合通常使用 Zero-based Index

第一筆 → Index 0
第二筆 → Index 1
第三筆 → Index 2

倒著執行

更新不一定只能使用:

i++;

也可以:

i--;

例如:

for (int i = 5; i >= 1; i--)
{
    Console.WriteLine(i);
}

結果:

5
4
3
2
1

3. while Loop

while 會在條件成立時持續執行。

基本語法:

while (condition)
{
    // 重複執行
}

例如:

int count = 1;

while (count <= 5)
{
    Console.WriteLine(count);
    count++;
}

結果:

1
2
3
4
5

只要:

count <= 5

還是 true,Loop 就會繼續。


for 還是 while

可以先這樣理解:

有明確計數方式
→ for

根據條件持續執行
→ while

例如:

執行 10 次
→ for

成功以前持續重試
→ while

這不是絕對規則,只是常見使用方式。


4. Infinite Loop:無限迴圈

如果條件永遠都是 true,Loop 就不會停止。

例如:

int count = 1;

while (count <= 5)
{
    Console.WriteLine(count);
}

因為 count 沒有改變,所以:

count <= 5

永遠都是 true

這就是:

Infinite Loop(無限迴圈)

應該更新 count

while (count <= 5)
{
    Console.WriteLine(count);
    count++;
}

寫 Loop 時要注意:

條件最後是否有機會變成 false?

如果練習時不小心造成 Infinite Loop,可以在 Terminal 使用:

Ctrl + C

停止程式。


5. do while

do while 的基本語法:

do
{
    // 重複執行
}
while (condition);

要注意最後有一個:

;

do whilewhile 最大的差異是:

while
→ 先判斷,再執行

do while
→ 先執行,再判斷

例如:

int count = 10;

while (count < 5)
{
    Console.WriteLine(count);
}

不會執行。

但:

int count = 10;

do
{
    Console.WriteLine(count);
}
while (count < 5);

會輸出:

10

所以:

do while 至少會執行一次。


6. breakcontinue

這兩個很常用來控制 Loop。

break
→ 結束整個 Loop

continue
→ 跳過這一次,繼續下一次

break

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break;
    }

    Console.WriteLine(i);
}

結果:

1
2
3
4

當:

i == 5

就直接離開 Loop。


continue

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue;
    }

    Console.WriteLine(i);
}

結果:

1
2
4
5

i == 3 時,只跳過這一次,Loop 還會繼續。


7. 實際範例:處理 Order

找到 Order 就停止

int targetOrderNumber = 6;

for (int orderNumber = 1; orderNumber <= 10; orderNumber++)
{
    Console.WriteLine($"Checking Order {orderNumber}");

    if (orderNumber == targetOrderNumber)
    {
        Console.WriteLine("Order Found");
        break;
    }
}

結果:

Checking Order 1
Checking Order 2
Checking Order 3
Checking Order 4
Checking Order 5
Checking Order 6
Order Found

找到指定 Order 後,就使用:

break;

停止繼續尋找。


跳過無效 Order

for (int orderNumber = 1; orderNumber <= 5; orderNumber++)
{
    if (orderNumber == 3)
    {
        continue;
    }

    Console.WriteLine($"Processing Order {orderNumber}");
}

結果:

Processing Order 1
Processing Order 2
Processing Order 4
Processing Order 5

可以理解成:

資料無效
↓
continue
↓
跳過這筆
↓
處理下一筆

8. Nested Loop

Loop 裡面還可以放另一個 Loop。

for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 2; j++)
    {
        Console.WriteLine($"i = {i}, j = {j}");
    }
}

結果:

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2

執行次數:

外層 3 次
×
內層 2 次
=
6 次

這稱為:

Nested Loop(巢狀迴圈)

目前先知道 Loop 可以放在另一個 Loop 裡即可。

今日練習


建立:

dotnet new console -n Day06Practice

練習一:輸出偶數

使用 for 走訪 1 ~ 10。

搭配:

number % 2 == 0

輸出:

2
4
6
8
10

練習二:continue

處理 Order 1 ~ 10。

如果 Order Number 是:

3
或
7

使用 continue 跳過。


練習三:break

建立:

int targetOrderNumber = 6;

從 Order 1 開始尋找。

找到後:

Order Found

並使用 break 停止 Loop。


練習四:while

建立:

int retryCount = 1;

當:

retryCount <= 3

時輸出:

Retry 1
Retry 2
Retry 3

每次執行後記得:

retryCount++;

Day 6 小結

今天最重要的是理解:

Loop 用來讓程式重複執行。

for

有明確計數方式
→ for

核心流程:

初始化
  ↓
判斷
  ↓
執行
  ↓
更新
  ↓
再次判斷

while

根據條件持續執行
→ while

do while

先執行
再判斷
→ 至少執行一次

break / continue

break
→ 結束 Loop

continue
→ 跳過這一次

寫 Loop 時最重要的是確認:

條件是否正確?

狀態是否有更新?

Loop 最後是否會停止?

參考資料:


上一篇
Day 5|Operator 與 Condition:運算、比較與條件判斷
下一篇
Day 7|Array:管理多筆相同 Type 的資料
系列文
現在就學C# 與 ASP.NET Core7
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言